﻿using System;
using System.Linq;
using System.Net.NetworkInformation;
using TcpLibrary;

namespace TcpClient
{
    class Program
    {
        static TcpLibrary.TcpClient tcpClient;
        static void Main(string[] args)
        {
            Console.Title = "TcpClient";

            string testIp = "192.168.8.61";

            tcpClient = new TestTcpClient(testIp, 4444);
            tcpClient.OptionKeepAlive = true;
            tcpClient.Connect();

            if (tcpClient.IsConnected)
            {
                Console.WriteLine("连接成功");
            }

            while (true)
            {
                System.Threading.Thread.Sleep(3000);

                //tcpClient.Send("hello");

                IPGlobalProperties ipProperties = IPGlobalProperties.GetIPGlobalProperties();

                var tcpResult = ipProperties.GetActiveTcpConnections();

                var tcpConnections = tcpResult.Where(t => t.LocalEndPoint.Port == 4444 || t.RemoteEndPoint.Port == 4444);

                if (tcpConnections.Count() > 0)
                {
                    foreach (var tcpConnection in tcpConnections)
                    {
                        Console.WriteLine($"local:{tcpConnection.LocalEndPoint} remote:{tcpConnection.RemoteEndPoint} state:{tcpConnection.State} {DateTime.Now.ToString("hh:MM:ss")}");
                    }
                }
                else
                {
                    Console.WriteLine($"连接不存在 {DateTime.Now.ToString("hh:MM:ss")}");
                }
            }
        }

        public class TestTcpSession : TcpLibrary.TcpSession
        {
            public TestTcpSession(TcpLibrary.TcpServer server) : base(server)
            {

            }
        }

        public class TestTcpClient : TcpLibrary.TcpClient
        {
            public TestTcpClient(string _ip, int _port) : base(_ip, _port)
            {
            }
            //public override long Receive(byte[] buffer)
            //{
            //    Console.WriteLine($"Receive：{buffer.ToString()}");
            //    return buffer.Length;
            //}
        }
    }
}
